import axios from "axios";
import store from "../store";
import router from "../router";
import { showNotify } from 'vant';
import { showLoadingToast, closeToast } from 'vant';
// 创建axios实例
const service = axios.create({
	baseURL: process.env.VUE_APP_BASE_URL, // api 的 VUE_APP_URL
	crossDomain: true,
	withCredentials: false,
	timeout: 8000 // 请求超时时间
});


// request拦截器,在请求之前做一些处理
service.interceptors.request.use(
	config => {
		// 给请求头添加请求字段
		console.log('request====', store.state.token);
		config.headers = {
			// "Authorization": store.state.token,
			"Content-Type": "application/json;charset=utf-8",
			'userType': "beijing_traffic",
			// "dataType": "json",
			'appversion': "V1.0.0",
			"Access-Control-Allow-Origin": "*"
		}
		// let appToken = store.st.token;
		config.data.appversion = "V1.0.0",
			config.data.token = store.state.token;
		if (!config.data.phoneNum) {
			config.data.phoneNum = store.state.userName;
		}
		showLoadingToast({
			duration: 0,
			message: '加载中...',
			forbidClick: true,
		});
		return config;
	},
	error => {
		closeToast();
		console.log('请求错误', error);
		showNotify('网络繁忙,稍后重试', error)
		Promise.reject(error);
	}
);
service.interceptors.response.use(
	response => {
		console.log('response', response.data);
		closeToast();
		if (response.data.result == 'SUCCESS') {
			console.log('response', 'SUCCESS');
			return Promise.resolve(response.data)
		} else if (response.data.result === "INVALID_TOKEN") {
			//token失效
			showNotify(response.data.msg || "请求错误");
			router.push("/login");
			store.commit('clearnToken');
			store.commit('clearnLocalStorage');
			return Promise.reject(response.data);
		} else {
			console.log('response', '数据返回错误');
			showNotify(response.data.msg || "数据返回错误");
			return Promise.reject(response.data);
		}
	},
	error => {
		closeToast();
		console.log('response', '响应错误');
		showNotify('网络繁忙,稍后重试!', error)
		console.log('响应错误', error);
		return Promise.reject(error);
	}
);
export default service;